package com.example.auth.controller;

import com.example.auth.feign.ThirdServerFeignService;
import com.example.auth.vo.UserRegistVo;
import com.example.common.constant.AuthServerConstant;
import com.example.common.exception.ExceptionCodeEnum;
import com.example.common.utils.R;
import com.example.common.utils.ValidateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ThirdServerFeignService thirdServerFeignService;
    @Value("${spring.redis.sms.expire-time}")
    private long expireTime;

    @GetMapping("/login")
    public String loginView() {
        return "login";
    }

    @GetMapping("/register")
    public String registerView() {
        return "reg";
    }

    /**
     * 发送短信验证码
     * @param phone
     * @return
     */
    @RequestMapping("/sms/sendcode")
    @ResponseBody
    public R sendCode(String phone) {
        String key = AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone;

        String redisCode = redisTemplate.opsForValue().get(key);
        // 1. 接口防刷
        // 判断同一手机号之前60s是否请求过接口
        if (!StringUtils.isEmpty(redisCode)) {
            String preTimeStr = redisCode.split("_")[1];
            long preTime = Long.parseLong(preTimeStr);
            long refreshTime = 60000;
            if (System.currentTimeMillis() - preTime <= refreshTime) {
                return R.error(ExceptionCodeEnum.FREQUENT_INTERFACE_REQ.getCode(),ExceptionCodeEnum.FREQUENT_INTERFACE_REQ.getMessage());
            }
        }
        // TODO 判断不同手机号恶意请求短信验证码接口

        // 2. 发送验证码
        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            stringBuilder.append(random.nextInt(10));
        }
        String code = stringBuilder.toString();
        // 将验证码保存到redis phone => code
        // 验证码需要加上请求的系统时间，接口防刷
        redisTemplate.opsForValue().set(key,code + "_" + System.currentTimeMillis(),expireTime, TimeUnit.MINUTES);
        thirdServerFeignService.sendCode(phone,code);
        return R.ok();
    }

    /**
     * 注册
     * @param registVo
     * @return
     */
    @RequestMapping("/reg")
    public String register(@Valid UserRegistVo registVo, BindingResult bindingResult, Model model) {
        if (bindingResult.hasErrors()) {
            Map<String, String> validationErrMsg = ValidateUtils.getValidationErrMsg(bindingResult);
            model.addAttribute("error",validationErrMsg);
        }
        return "redirect:http://auth.gmall.com/login";
    }
}
